﻿

namespace OneWorks.Application
{
    using System;
    using Interface;
    using Entity;
    using Metadata.Entity;
    using Metadata.Enum;
    using Repositories.EntityFramework;
    using Repositories.Interface;
    using Utils.Specifications;

    public class IconServer : BaseService, IIconService
    {
        private readonly IIconRepository _iconRepository;

        static IconServer()
        {
            AutoMapper.Mapper.CreateMap<DataBase.Entity.Icon, Icon>();
            AutoMapper.Mapper.CreateMap<Icon, DataBase.Entity.Icon>();
        }

        public IconServer()
        {
            _iconRepository = new IconRepository(RepositoryContext);
        }

        public RunResult<Icon> Add(Icon icon)
        {
            RunResult<Icon> runResult = new RunResult<Icon>();
            try
            {
                if (_iconRepository.Exists(Specification<DataBase.Entity.Icon>.Eval(i => i.Style == icon.Style )))
                {
                    return new RunResult<Icon>
                    {
                        Status = ResultStatus.Failure,
                        Message = "图标样式已经存在"
                    };
                }
                DataBase.Entity.Icon dbIcon = AutoMapper.Mapper.Map<Icon, DataBase.Entity.Icon>(icon);
                dbIcon.ID = Guid.NewGuid();
                _iconRepository.Add(dbIcon);
                int r = RepositoryContext.Commit();
                if (r > 0)
                {
                    runResult.Status = ResultStatus.Success;
                    runResult.Message = "图标添加成功";
                    icon.IconID = dbIcon.ID;
                    runResult.Result = icon;
                }
                else
                {
                    runResult.Status = ResultStatus.Failure;
                    runResult.Message = "图标添加数据库操作失败";
                }
            }
            catch (Exception exception)
            {
                runResult.Status = ResultStatus.Abnormal;
                runResult.Message = "图标添加出现异常";
                runResult.Exception = exception;
            }
            return runResult;
        }

        public RunResult<bool> Exists(string style)
        {
            RunResult<bool> runResult = new RunResult<bool>();
            try
            {
                runResult.Status = ResultStatus.Success;
                runResult.Result = _iconRepository.Exists(Specification<DataBase.Entity.Icon>.Eval(i => i.Style == style));
            }
            catch (Exception exception)
            {                
                runResult.Exception = exception;
                runResult.Message = string.Format("验证图片是否存在异常,参数{0}", style);
                runResult.Status = ResultStatus.Abnormal;
            }
            return runResult;
        }
    }
}
